package udp;

import java.io.IOException;
import java.net.*;

/**
 * @description:
 * @author: jhy
 * @time: 2021/4/18 13:27
 */

//基于UDP通信的 发送端B
public class UDPSendB {

    public static void main(String[] args) throws IOException {

        //1.创建一个DatagramSocket对象,让其在9998端口监听
        //udp通信中，互为发送端和接收端
        DatagramSocket socket = new DatagramSocket(9998);

        //2.将要发送的数据封装到DatagramPacket中
        byte[] bytes = "Hello,明天恰火锅".getBytes();
        //参数：数据  目标主机  端口
        DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length, InetAddress.getByName("192.168.171.1"), 9999);

        //3.使用socket的send(DatagramPacket)方法发送数据
        socket.send(packet);

        //4.使用socket的receive(DatagramPacket)接收回应的数据
        byte[] bytes1 = new byte[1024];
        packet = new DatagramPacket(bytes1,0,bytes1.length);
        socket.receive(packet);
        //5.将接收到的DatagramPacket进行拆包
        int length = packet.getLength();
        byte[] data = packet.getData();
        System.out.println(new String(data,0,length));

        //关闭资源
        socket.close();
    }
}
